package com.minelx.table.core;

import com.minelx.table.core.series.Series;
import com.minelx.table.core.series.source.ArrayGridSource;
import com.minelx.table.core.series.source.GridSource;

import java.util.Arrays;

public class Tables {
	public static Table grid(GridSource<String> gridSource) {
		return create(new GridTableProvider(gridSource));
	}

	public static Table rowIndexed(Table decorated, Series<Boolean> booleanIndexes) {
		return create(new RowBoolIndexedTableProvider(decorated, booleanIndexes));
	}

	public static Table columnIndexed(Table decorated, Series<Boolean> booleanIndexes) {
		return create(new ColumnBoolIndexedTableProvider(decorated, booleanIndexes));
	}

	public static Table innerJoined(Table left, Table right, String leftOn, String rightOn) {
		return create(new InnerMergingTableProvider(left, right, leftOn, rightOn));
	}

	public static Table csv(String source) {
		String[] lines = source.split("\r\n|\n");
		int titleLength = lines[0].split(",", -1).length;

		// building grid
		String[][] grid = new String[lines.length][];
		for (int lineAt = 0; lineAt < lines.length; lineAt++) {
			String[] lineCells = lines[lineAt].split(",", -1);
			if (lineCells.length == titleLength) { // column count matched
				grid[lineAt] = lineCells;
			} else { // column count mismatched, fill the array length
				grid[lineAt] = Arrays.copyOf(lineCells, titleLength);
				Arrays.fill(grid[lineAt], lineCells.length, grid[lineAt].length, "");
			}
		}
		return grid(new ArrayGridSource<>(grid));
	}

	public static Table create(TableProvider tableProvider) {
		return new Table(tableProvider);
	}
}
